from service import Service
from model.requirement import RequirementDao
from lib.validator import Validator
from lib.form import Form
from bson.objectid import ObjectId
import time

class RequirementService(Service):
    def __init__(self):
        self.dao = RequirementDao()

    def get_requirement(self, sid):
        """
        Argument:
            sid -- string type
        """
        if sid != '':
            oid = ObjectId(sid)
            requirement = self.dao.find_one({'_id':oid})
            return self.get_dict(requirement)
        else:
            return None
        
    def delete_requirement(self, sid):
        if sid != '':
            oid = ObjectId(sid)
            self.dao.remove({'_id':oid})
    
    def get_requirements(self, query={}):
        """ Get the requirements for rendering the html
        """
        requirements = self.dao.find(query)
        
        if requirements is not None:
            _requirements = []
            for requirement in requirements:
                _requirements.append(self.get_dict(requirement))
            return _requirements
        else:
            return []
        
    def get_sprint_oid(self, requirement_id):
        _requirement = self.dao.find_one({'_id':ObjectId(requirement_id)})
        if _requirement is None:
            return None
        else:
            return _requirement['project_id']

    def check_in(self, ids):
        _ids = [ObjectId(sid) for sid in ids]
        reqs = self.dao.find({'_id': {'$in': _ids }})
        for _req in reqs:
            _req['in_backlog'] = 1
            self.dao.save(_req)
        return self.get_requirements({'_id': {'$in': _ids }})
    
    def check_out(self, ids, sprint_id):
        _ids = [ObjectId(sid) for sid in ids]
        reqs = self.dao.find({'_id': {'$in': _ids }})
        for _req in reqs:
            _req['in_backlog'] = 0
            _req['sprint_id'] = sprint_id
            self.dao.save(_req)
        return self.get_requirements({'_id': {'$in': _ids }})
            
    def submit_requirement(self, _dict, mode):
        """
        Return:
        The '_id' value of to_save or [None] if manipulate is False and to_save has no _id field.
        """
        _input = self.get_dao_input(_dict, mode)
        
        if mode == 'edit':
            _input['created'] = _dict['created']
            _input['in_backlog'] = int(_input['in_backlog'])
        else:
            _input['created'] = time.time()
            _input['in_backlog'] = 1
        return self.dao.save(_input)

    def update_requirement(self, _dict):
        """
        Return:
        The '_id' value of to_save or [None] if manipulate is False and to_save has no _id field.
        """
        _input = self.get_dao_input(_dict, 'edit')
        return self.dao.update({'_id':_input['_id']}, _input)

    
    def get_backlog_tree(self):
        requirement_dao = RequirementDao()
        _requirements = [] 
        requirements = requirement_dao.find()
        for requirement in requirements:
            sid = str(requirement['_id'])
            label = '<a href="/requirement_view">' + requirement['name'] + '</a>'
            _requirements.append({'id':sid, 'label':label})
            
        return [{'id':'0' ,'label':'Backlog', 'children':_requirements}]

class RequirementValidator(Validator):
    def __init__(self):
        Validator.__init__(self)
              
        self.rules = {'name': { 
                                'required' : [None, True],
                                'minlength':[None, 1],
                                'maxlength':[None, 256]
                                },
                      'description': { 
                                'maxlength':[None, 256]
                                }
        }

    
class RequirementForm(Form):
    """ Submit user form
    """
    def __init__(self):
        """Only accept POST request
        """
        Form.__init__(self)
        self.validator = RequirementValidator()
        
        if self.is_submitted():
            self.errors = self.validator.validate(self.input)
            #self.inputs = self.get_inputs(self.raw_inputs)


    
    def has_error(self):
        return self.errors != []

